package cn.liangcaomei.eduservice.service.impl;

import cn.liangcaomei.eduservice.client.VodClient;
import cn.liangcaomei.eduservice.entity.EduVideo;
import cn.liangcaomei.eduservice.mapper.EduVideoMapper;
import cn.liangcaomei.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author LiuJie
 * @since 2024-01-27
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    //根据课程id 删除小节
    //删除小节之前，需要先删除视频，如果有
    @Override
    public void removeVideoCourseId(String courseId) {
        //1 根据课程id查询课程所有的视频id
        QueryWrapper<EduVideo> vWrapper = new QueryWrapper<>();
        vWrapper.eq("course_id", courseId);
        vWrapper.select("video_source_id");
        List<EduVideo> eduVideosList = baseMapper.selectList(vWrapper);

        //List<EduVideo> 变成 List<String>
        List<String> videoIds = new ArrayList<>();
        for (int i = 0; i < eduVideosList.size(); i++) {
            EduVideo eduVideo = eduVideosList.get(i);
            String videoSourceId = eduVideo.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)) {
                videoIds.add(videoSourceId);
            }
        }
        if (videoIds.size() > 0) {
            //通过调远程方法批量删除阿里云视频
            vodClient.deleteBatch(videoIds);
        }

        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        baseMapper.delete(wrapper);
    }
}
